package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.exceptions.PersistenceException;
import org.example.domain.dto.LoginDto;
import org.example.domain.entity.Users;
import org.example.domain.model.Result;
import org.example.mapper.FmFrontedLoginMapper;
import org.example.prop.OssProperties;
import org.example.service.IFmFrontedSysUserService;
import org.example.util.FmFrontedJwtUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

@Service
public class FmFrontedSysUserServiceImpl implements IFmFrontedSysUserService {
    private FmFrontedLoginMapper fmFrontedLoginMapper;
    private PasswordEncoder passwordEncoder;
    private FmFrontedJwtUtils fmFrontedJwtUtils;
    private OssProperties properties;
    private Log log= LogFactory.getLog(FmFrontedSysUserServiceImpl.class);


    public FmFrontedSysUserServiceImpl(FmFrontedLoginMapper fmFrontedLoginMapper, PasswordEncoder passwordEncoder, FmFrontedJwtUtils fmFrontedJwtUtils, OssProperties properties) {
        this.fmFrontedLoginMapper = fmFrontedLoginMapper;
        this.passwordEncoder = passwordEncoder;
        this.fmFrontedJwtUtils = fmFrontedJwtUtils;
        this.properties = properties;
    }

    @Override
    public Result login(LoginDto loginDto) {
        //todo 需要验证用户名和密码是否正确，如果正确则需要颁发access_token和refresh_token
        QueryWrapper<Users> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",loginDto.getUsername());
        Users users = fmFrontedLoginMapper.selectOne(queryWrapper);

        if (users == null || users.getUserStatus()==-1||!passwordEncoder.matches(loginDto.getPassword(), users.getPassword())){
            return Result.buildFail("用户名或密码不正确");
        }else{
            Map<String ,String> tokens=new HashMap<>();
            String username=loginDto.getUsername();
            tokens.put(FmFrontedJwtUtils.ACCESS_TOKEN_KEY, fmFrontedJwtUtils.createAccessToken(username));
            log.info(tokens.get(0));
            tokens.put(FmFrontedJwtUtils.REFRESH_TOKEN_KEY, fmFrontedJwtUtils.createRefreshToken(username));
            /**
             * tokens存放"access_token" value和"refresh_token" value
             */
            return Result.buildSuccess(tokens);
        }
    }
    @Override
    public Users queryUserByName(String userName){
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("username", userName);
        Users users = fmFrontedLoginMapper.selectOne(usersQueryWrapper);
        if (users!=null){
            users.setPassword("");
            users.setUserImg("https://fzlbkt.oss-cn-hangzhou.aliyuncs.com/exampledir/"+users.getUserImg());
//            users.setUserImg(properties.getBucketURL()+users.getUserImg());
        }
        return users;
    }
    @Override
    public String registeredUser(Map<String,String> userMessage){
        try {
            Users users=new Users();
            users.setUsername(userMessage.get("username"));
            users.setUserStatus(1);
            users.setPassword(passwordEncoder.encode(userMessage.get("password")));
            users.setRealname(userMessage.get("realname"));
            users.setUserMobile(userMessage.get("phone"));
            users.setUserEmail(userMessage.get("email"));
            String birth = userMessage.get("birth");
            String[] ts = birth.split("T");
            users.setUserBirth(LocalDate.parse(ts[0]));
            fmFrontedLoginMapper.insert(users);
            return "success";
        }catch (Exception e){
                if(e.getCause()!=null && "java.sql.SQLIntegrityConstraintViolationException".equals(e.getCause().getClass().getName())){
                    // 唯一约束异常
                    return "onlyName";
                }else {
                    return "fail";
                }
            }



        }




}
